package com.deyuanyun.pic.pig.service.impl;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.deyuanyun.pic.common.exception.PicException;
import com.deyuanyun.pic.common.spring.SpringAppliction;
import com.deyuanyun.pic.common.util.DateUtil;
import com.deyuanyun.pic.common.util.ObjectUtil;
import com.deyuanyun.pic.common.util.UploadUtil;
import com.deyuanyun.pic.domain.pipe.PipeLine;
import com.deyuanyun.pic.mapper.pipe.InsspSegmentMapper;
import com.deyuanyun.pic.mapper.pipe.PipeLineMapper;
import com.deyuanyun.pic.pig.domain.CleanPipeLineManagerVo;
import com.deyuanyun.pic.pig.domain.InspSegment;
import com.deyuanyun.pic.pig.domain.PigResults;
import com.deyuanyun.pic.pig.domain.PigTask;
import com.deyuanyun.pic.pig.domain.PigTaskPoint;
import com.deyuanyun.pic.pig.domain.PointVO;
import com.deyuanyun.pic.pig.domain.TrackPointExportVO;
import com.deyuanyun.pic.pig.domain.TrackPointImportVO;
import com.deyuanyun.pic.pig.mapper.InspSegmentMapper;
import com.deyuanyun.pic.pig.mapper.PigResultsMapper;
import com.deyuanyun.pic.pig.mapper.PigTaskMapper;
import com.deyuanyun.pic.pig.mapper.PigTaskPointMapper;
import com.deyuanyun.pic.pig.service.CleanPipeLineTrackService;
import com.deyuanyun.pic.pig.service.MoitoService;
import com.deyuanyun.pic.pig.service.RealTimeMoioService;
import com.deyuanyun.pic.pig.util.PiggingUtil;
import com.deyuanyun.pic.support.biz.CodeUtil;

@Service
public class CleanPipeLineTrackServiceImpl implements CleanPipeLineTrackService {
	// 进行中
	private static final short statusFlag3 = 3;
	// 已完成
	private static final short statusFlag4 = 4;

	// 导出跟踪的excel的列数
	private static final int columns = 9;

	@Resource
	private PigTaskMapper pigTaskMapper;
	@Resource
	private PigTaskPointMapper pigTaskPointMapper;
	@Resource
	private PipeLineMapper pipeLineMapper;
	@Resource
	private InspSegmentMapper inspSegmentMapper;
	@Resource
	private PigResultsMapper pigResultsMapper;

	private MoitoService moitoService;

	private static final String imgUrl = UploadUtil.SOURCE + UploadUtil.IMGURL;

	@Autowired
	public CleanPipeLineTrackServiceImpl(SpringAppliction appliction) {
		moitoService = (MoitoService) SpringAppliction.getBean(RealTimeMoioService.class);
	}

	@Override
	public List getCleanPipeLineTrackIndex(CleanPipeLineManagerVo vo) {
		return pigTaskPointMapper.getCleanPipeLineTrackIndex(vo);
	}

	@Override
	public List<PigTaskPoint> getInspTaskPointByTaskId(String taskId) {
		List<PigTaskPoint> list = new ArrayList<PigTaskPoint>();
		Map<String, Object> reMap = new HashMap<String, Object>();
		String reverse = pigTaskMapper.selectReverseByTaskId(taskId);
		if (!StringUtils.isEmpty(reverse)) {
			reMap.put("taskId", taskId);
			reMap.put("reverse", reverse);
			list = pigTaskPointMapper.getInspTaskPointByTaskId(reMap);
		}
		return list;
	}

	@Override
	public Map<String, Object> getInspMonitorByTaskId(String taskId, Map<String, Object> map) {
		CleanPipeLineManagerVo ls = pigTaskPointMapper.getPigByTaskId(taskId);
		map.put("pig", ls);
		if(ObjectUtil.isNotNullEmpty(ls.getEndTime())){
			List res = pigTaskPointMapper.findPigResultForDialog(taskId);
			map.put("res", res);
		}
		return map;
	}

	@Override
	public List<TrackPointExportVO> excelExport(String taskId) {
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("taskId", taskId);
		String reverse = pigTaskMapper.selectReverseByTaskId(taskId);
		if(!StringUtils.isEmpty(reverse)){
			map.put("reverse", reverse);
		}
		return pigTaskPointMapper.excelExport(map);
	}

	@Override
	public int saveTaskTrack(String taskId) {
		int num = 0;
		try {
			PigTask t = pigTaskMapper.selectByPrimaryKey(taskId);
			t.setStaus(statusFlag4);
			num = pigTaskMapper.updateByPrimaryKeySelective(t);

		} catch (PicException e) {
			e.printStackTrace();
		}
		return num;
	}

	// 日期转换（STRING - DATA）
	public static Date convertStringToDate(String dateStr) throws ParseException {
		if (dateStr == null || "".equals(dateStr)) {
			return null;
		}
		DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return sdf.parse(dateStr);
	}

	@Override
	public List selectPigByPigNumber(String pigNum) {
		return pigTaskMapper.selectPigByPigNumber(pigNum);
	}

	@Override
	public List<HashMap> getMonito(Map param) {
		List<HashMap> result = new ArrayList<HashMap>();
		List<HashMap> data = null;

		// 实时获取监控数据服务是否初始化成功，如果初始化成功就调用实时监控数据服务
		if (moitoService != null) {
			data = moitoService.getMonito(param);
		}
		// 如果实时监控服务未调用成功 则使用数据库数据
		if (data == null) {
			data = pigTaskPointMapper.getMonito(param);

			HashMap info = null;
			for (int i = 0; i < data.size(); i++) {
				HashMap map = data.get(i);

				map.put("typeName", map.get("typeName".toUpperCase()));
				map.put("passedTime", map.get("passedTime".toUpperCase()));
				map.put("gisId", map.get("gisId".toUpperCase()));
				map.remove("typeName".toUpperCase());
				map.remove("passedTime".toUpperCase());
				map.remove("gisId".toUpperCase());
				result.add(map);
			}
		}
		return result;
	}

	@Override
	public String getMonitoGisPoint(Map param) {
		List<HashMap> data = pigTaskPointMapper.getMonitoGisPoint(param);
		StringBuffer json = new StringBuffer("[{\"typeName\":\"piggingstructure\",");
		json.append("\"gisIdArray\":[");
		for (int i = 0; i < data.size(); i++) {
			Map map = data.get(i);
			json.append("\"").append(map.get("GISID")).append("\",");
			if (i == 1) {
				json = json.deleteCharAt(json.length() - 1);
				json.append("]},{\"typeName\":\"marker\",gisIdArray:[");
			}
		}
		json = json.deleteCharAt(json.length() - 1);
		json.append("]}]");

		return json.toString();
	}

	@SuppressWarnings("rawtypes")
	@Override
	public Map<String, Object> getTrackDetail(String taskId, Map<String, Object> map) {
		PigTask task = pigTaskMapper.selectByPrimaryKey(taskId);
		boolean flag = false;
		if (null != task) {
			if (task.getStaus().equals(statusFlag3)) {
				flag = true;
			}
			PipeLine pl = pipeLineMapper.selectByPrimaryKey(task.getPipeLineId());
			InspSegment segment = inspSegmentMapper.selectByPrimaryKey(task.getInspSegmentId());
			// 收发球同
			Map<String,Object> reMap = new HashMap<String,Object>();
			reMap.put("segmentId", null);
			reMap.put("taskId", taskId);
			CleanPipeLineManagerVo vo = pigTaskMapper.getPigByInspSegmentId(reMap);
			// 该任务需要通过的跟踪点
			List point = null;
			String reverse = pigTaskMapper.selectReverseByTaskId(taskId);
			if(!StringUtils.isEmpty(reverse)){
				reMap.put("reverse", reverse);
				point = pigTaskPointMapper.getInspTaskPointByTaskId(reMap);
			}
			// 该任务已经通过的跟踪点
			// List passPoint =
			// pigTaskPointMapper.getPassPointByTaskId(task.getId());
			PigResults pr = pigResultsMapper.getDetail(taskId);
			List imgList = PiggingUtil.searchImg(imgUrl, taskId, null, false, true);
			map.put("task", task);
			map.put("pipeLine", pl);
			map.put("segment", segment);
			map.put("pig", vo);
			map.put("point", point);
			map.put("result", pr);
			map.put("imgList", imgList);
			if(ObjectUtil.isNotNullEmpty(vo.getEndTime())){
				List res = pigTaskPointMapper.findPigResultForDialog(taskId);
				map.put("res", res);
			}
		}
		map.put("flag", flag);
		return map;
	}

	@Override
	public Map<String, Object> getPointDetailByPointCode(String pointId, String taskId) {
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Object> praMap = new HashMap<String, Object>();
		praMap.put("pointId", pointId);
		praMap.put("taskId", taskId);
		List ls = pigTaskPointMapper.getPointDetailByPointCode(praMap);
		map.put("pointDetail", null == ls.get(0) ? null : ls.get(0));
		List imgList = PiggingUtil.searchImg(imgUrl, taskId, pointId, true, false);
		map.put("img", imgList);
		return map;
	}

	private double avgSpeed(double mile, double time) {
		BigDecimal value = new BigDecimal(mile / time);
		value = value.setScale(2, BigDecimal.ROUND_HALF_UP);
		return value.doubleValue();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List getTrackPointByTaskId(String taskId) throws Exception {
		List list = new ArrayList();
		Map<String, Object> map = null;
		List<PointVO> point = null;
		String reverse = pigTaskMapper.selectReverseByTaskId(taskId);
		if(!StringUtils.isEmpty(reverse)){
			Map<String,Object> reMap = new HashMap<String, Object>();
			reMap.put("taskId", taskId);
			reMap.put("reverse", reverse);
			point = pigTaskPointMapper.getTrackPointByTaskId(reMap);
		}
		for (PointVO p : point) {
			map = new HashMap<String, Object>();
			map.put("customnumber", p.getCustomnumber());
			map.put("lng", p.getLng());
			map.put("lat", p.getLat());
			map.put("code", p.getCode());
			map.put("name", p.getName());
			map.put("reference", p.getReference());
			map.put("remark", p.getRemark());
			map.put("lineName", p.getLineName());
			map.put("segmentName", p.getSegmentName());
			map.put("regionName", p.getRegionName());
			map.put("recorder", p.getRecrder());
			map.put("passTime", StringUtils.isEmpty(p.getPassTime()) ? "" : p.getPassTime());
			map.put("gisId", p.getGisid());
			map.put("mileage", p.getMileage());
			map.put("avgSpeed", p.getAvgSpeed());
			if (StringUtils.isEmpty(p.getPassTime())) {
				map.put("state", "N");
			} else {
				map.put("state", "Y");
			}
			map.put("zuobiao", p.getLng() + "," + p.getLat());
			map.put("type", CodeUtil.getName(p.getType()));
			list.add(map);
		}
		return list;
	}

	private String covertCode(String code) throws IOException {
		String bianma = null;
		if (!StringUtils.isEmpty(code)) {
			byte[] jiema = code.getBytes("gb2312"); // 解码
			bianma = new String(jiema, "UTF-8");// 编码 如果上面的解码不对 可能出现问题
		}
		return bianma;
	}

	/**
	 * 将字符编码转换成UTF-16码
	 */
	public String toUTF_16(String str) throws UnsupportedEncodingException {
		return this.changeCharset(str, "UTF_16");
	}

	/**
	 * 将字符编码转换成GBK码
	 */
	public String toGBK(String str) throws UnsupportedEncodingException {
		return this.changeCharset(str, "GBK");
	}

	/**
	 * 字符串编码转换的实现方法
	 * 
	 * @param str
	 *            待转换编码的字符串
	 * @param newCharset
	 *            目标编码
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public String changeCharset(String str, String newCharset) throws UnsupportedEncodingException {
		if (!StringUtils.isEmpty(str)) {
			// 用默认字符编码解码字符串。
			byte[] bs = str.getBytes();
			// 用新的字符编码生成字符串
			return new String(bs, newCharset);
		}
		return null;
	}

	/**
	 * 字符串编码转换的实现方法
	 * 
	 * @param str
	 *            待转换编码的字符串
	 * @param oldCharset
	 *            原编码
	 * @param newCharset
	 *            目标编码
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public String changeCharset(String str, String oldCharset, String newCharset) throws UnsupportedEncodingException {
		if (str != null) {
			// 用旧的字符编码解码字符串。解码可能会出现异常。
			byte[] bs = str.getBytes(oldCharset);
			// 用新的字符编码生成字符串
			return new String(bs, newCharset);
		}
		return null;
	}

	@Override
	public Map<String, Object> getViewImg(String taskId, String pointId, Map<String, Object> map) {
		String fileUrl = UploadUtil.SOURCE + UploadUtil.IMGURL;
		Map<String, Object> praMap = new HashMap<String, Object>();
		praMap.put("taskId", taskId);
		praMap.put("pointId", pointId);
		praMap.put("fileUrl", fileUrl);
		List<PointVO> list = pigTaskPointMapper.getViewImg(praMap);
		if (list.size() > 0) {
			map.put("oneImg", list.get(0).getPath());
		}
		map.put("imgList", list);
		return map;
	}

	/*
	 * @Override public String importPoint(String taskId, MultipartFile file)
	 * throws Exception { StringBuffer sb = new StringBuffer();
	 * //导出的excel名称中的任务Id String sheetNameTaskId = ""; int m = 0; int count = 0;
	 * InputStream is = null; Workbook book = null; PigTaskPoint tp = null ;
	 * if(StringUtils.isEmpty(taskId)){ //任务不存在 return
	 * sb.append("_sb01").toString(); }else{ String fileName =
	 * file.getOriginalFilename(); is = file.getInputStream(); WorkbookSettings
	 * wbs = new WorkbookSettings(); wbs.setEncoding("GBK"); // 解决中文乱码 book =
	 * Workbook.getWorkbook(is,wbs);// 获得一个工作表对象 Sheet sheet =
	 * book.getSheet(0);// 取得第一个工作表 //获取上传文件中的任务Id int begin =
	 * fileName.indexOf("[") + 1; int end = fileName.lastIndexOf("]");
	 * sheetNameTaskId = fileName.substring(begin, end); //判断是否是同一个任务的跟踪点
	 * if(!sheetNameTaskId.equals(taskId)){ return
	 * sb.append("_sb02").toString(); }else{ int len = sheet.getRows() - 1;//
	 * 取得行数减去标题 int wid = sheet.getColumns();//取得列数 //获取该检测任务通过的跟踪点集合
	 * List<PigTaskPoint> rs =
	 * pigTaskPointMapper.getInspTaskPointByTaskId(taskId);
	 * //判断excel表中的行数和数据库中查询的行数是否相同 if(len != rs.size()){ return
	 * sb.append("_sb03").toString(); } //判断excel表中的列数和数据库中查询的列数是否相同 else if(wid
	 * != columns){ return sb.append("_sb03").toString(); }else{
	 * //遍历行,过滤sheet的第一行 m = rs.size(); for (int i = 1; i <= len; i++) { //
	 * 已通过的跟踪点Id String id =""; //通过时间 String passTime =""; //记录人 String
	 * recorder = ""; //备注 String remark = ""; // 获得一行的所有单元格 Cell[] row =
	 * sheet.getRow(i); for (int j = 0; j < row.length; j++) { // 获得单元格内容 String
	 * cellContent = row[j].getContents().trim(); //跟踪点通过记录 if(j == 0){ tp =
	 * pigTaskPointMapper.selectByPrimaryKey(cellContent); int co = 0; if(tp ==
	 * null ){ co ++; return sb.append("_sb04").toString(); } if(co > 0){ break;
	 * } id = tp.getId(); } //通过时间格式化 if (j == 6) { passTime = cellContent; }
	 * if(j == 7){ recorder = cellContent; } if(j == 8){ remark = cellContent; }
	 * } if (!"".equals(id) && null != id && !"".equals(passTime) && null !=
	 * passTime && !"".equals(recorder) && null != recorder &&
	 * !"".equals(remark) && null != remark && null != tp) { //更新通过跟踪表Id=id的记录
	 * tp.setPassTime(convertStringToDate(passTime)); tp.setRecrder(recorder);
	 * tp.setCreateRemark(remark);
	 * pigTaskPointMapper.updateByPrimaryKeySelective(tp); count ++; } } if(m ==
	 * count){ //跟新任务状态 为进行中 PigTask t =
	 * pigTaskMapper.selectByPrimaryKey(taskId); t.setStaus(statusFlag3);
	 * pigTaskMapper.updateByPrimaryKeySelective(t); //导入成功 //
	 * sb.append("_sb06"); } } } } if (is!=null){ is.close(); } return
	 * sb.toString(); }
	 */

	@Override
	public int importTrackPoint(List<TrackPointImportVO> finalInfo, String taskId) throws Exception {
		int count = 0;
		PigTask t = pigTaskMapper.selectByPrimaryKey(taskId);
		if (ObjectUtil.isNotNullEmpty(finalInfo) && ObjectUtil.isNotNullEmpty(t)) {
			// 获取该任务在数据库中的跟踪点
			List<PointVO> ls = null;
			String reverse = pigTaskMapper.selectReverseByTaskId(taskId);
			if(!StringUtils.isEmpty(reverse)){
				Map<String,Object> map = new HashMap<String,Object>();
				map.put("taskId", taskId);
				map.put("reverse", reverse);
				ls = pigTaskPointMapper.getTrackPointByTaskId(map);
			}
			String dataSourceId = "";
			StringBuffer dataSource = new StringBuffer();
			if (ls.size() > 0) {
				for (PointVO pointVO : ls) {
					dataSource.append(pointVO.getDataSourceId()).append(",");
				}
			}
			dataSourceId = dataSource.toString();
			if (!StringUtils.isEmpty(dataSourceId)) {
				for (TrackPointImportVO impVo : finalInfo) {
					
					/* 
					 * 使用数据库中的跟踪点id和excel中的id编号做对比，如果存在则修改。如果excel存在相同的id编号且和数据库中的
					 * id能匹配上责覆盖上次更新的数据 
					 */
					if (dataSourceId.contains(impVo.getId())) {
						PigTaskPoint tp = pigTaskPointMapper.selectByPrimaryKey(impVo.getId());
						tp.setPassTime(DateUtil.allStr2Date(impVo.getPassTime()));
						tp.setRecrder(impVo.getRecorder());
						tp.setCreateRemark(impVo.getRemark());
						pigTaskPointMapper.updateByPrimaryKeySelective(tp);
						count++;
					}
				}
				if (count > 0) { // 表示有跟踪点更新成功
					t.setStaus(statusFlag3);
					pigTaskMapper.updateByPrimaryKeySelective(t);
				}
			}
		}
		return count;
	}

	@Override
	public List loadTrackPoint(String taskId) {
		List point = null;
		Map<String,Object> reMap = new HashMap<String,Object>();
		String reverse = pigTaskMapper.selectReverseByTaskId(taskId);
		reMap.put("taskId", taskId);
		if(!StringUtils.isEmpty(reverse)){
			reMap.put("reverse", reverse);
			point = pigTaskPointMapper.getInspTaskPointByTaskId(reMap);
		}
		return point;
	}

	@Override
	public String selectReverseByTaskId(String taskId) {
		return  pigTaskMapper.selectReverseByTaskId(taskId);
	}

}
